package com.xiaoyun.rollutil.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoyun.rollutil.config.AddressMap;
import com.xiaoyun.rollutil.entity.WeatherInfo;
import com.xiaoyun.rollutil.entity.bo.ApiModelBO;
import com.xiaoyun.rollutil.mapper.WeatherInfoMapper;
import com.xiaoyun.rollutil.service.IWeatherService;
import com.xiaoyun.rollutil.util.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author: XiaoYun461
 * @Date: 2021/12/2 18:33
 */
@Service
@AllArgsConstructor
@Slf4j
public class WeatherServiceImpl implements IWeatherService {

    private final WeatherInfoMapper weatherInfoMapper;

    private final AddressMap addressMap;


    @Override
    public WeatherInfo getCurrentWeatherByCode(String cityCode) {
        List<WeatherInfo> weatherInfos = weatherInfoMapper
                .selectList(new LambdaQueryWrapper<WeatherInfo>()
                        .eq(WeatherInfo::getCityCode, cityCode)
                        .orderByDesc(WeatherInfo::getReportTime));
        if (CollUtil.isNotEmpty(weatherInfos) && checkCurrentTime(weatherInfos.get(0).getReportTime())) {
            return weatherInfos.get(0);
        }
        String cityName = addressMap.getCityNameByCode(cityCode);

        ApiModelBO apiModelBO = RequestUtil.getTodayWeatherModel(cityName);
        if (apiModelBO.isSuccess()) {
            WeatherInfo newWeatherInfo = JSONUtil.toBean((JSONObject) apiModelBO.getData(), WeatherInfo.class);
            weatherInfoMapper.insert(newWeatherInfo);
            return newWeatherInfo;
        } else {
            log.info("请求错误 该城市为:{}, 描述信息为:{}", cityName, apiModelBO.getMsg());
            return null;
        }
    }

    /**
     * 检查是否为当日时间
     *
     * @param reportTime
     * @return
     */
    private boolean checkCurrentTime(LocalDateTime reportTime) {
        LocalDate localDate = reportTime.toLocalDate();
        LocalDate nowLocalDate = LocalDateTime.now().toLocalDate();
        return Objects.equals(localDate.toString(), nowLocalDate.toString());
    }

}
